#include <string.h>
#include <stdlib.h>

#include "sym_list.h"

static void symbol_free(Symbol *sym)
{
	if (sym->priv)
		free(sym->priv);
	free(sym);
}

void symlist_free(SymList *sl)
{
	while (sl->sym_list)
		symlist_delete(sl->sym_list);
	free(sl);
}

Symbol* symlist_add(SymList *sl, char *name)
{
	Symbol *sym;
	assert(sl);
	assert(name);
	sym = malloc(sizeof(Symbol));
	memset(sym, 0, sizeof(Symbol));
	sym->name = strdup(name);
	if (sl->sym_list) {
		sym->prev = sl->sym_list->prev;
		sym->next = sl->sym_list;
		sl->sym_list->prev = sym;
	} else {
		sl->sym_list = sym;
		sym->prev = sym->next = sym;
	}
	return sym;
}

void symlist_delete(SymList *sl, Symbol *sym)
{
	if (sym->prev == sym->next) {
		symbol_free(sym);
		sl->sym_list = NULL;
	}
	if (sym == sl->sym_list)
		sl->sym_list = sym->next;
	sym->prev->next = sym->next;
	sym->next->prev = sym->prev;
	symbol_free(sym);
}

Symbol* symlist_match(SymList *sl, char *name)
{
	Symbol *cur;
	if(!sl->sym_list)
		return NULL;
	cur = sl->sym_list;
	do {
		if(!strcmp(cur->name, name))
			return cur;
		cur = cur->next;
	} while(cur != sl->sym_list);
	return NULL;
}
